<template>
    <div class="datalist">
        <Row>
            <Col :xs="24">
                <Button
                    type="primary"
                    @click="add"
                    class="addbutton"
                    style="width: 51px; height: 35px"
                >
                    <i
                        class="iconfont icon-add"
                        style="font-size: 14px; margin-right: 5px"
                    ></i>
                </Button>
                <Select
                    class="w-select"
                    clearable
                    v-model="searchStatus"
                    placeholder="状态"
                >
                    <Option value="1">启用</Option>
                    <Option value="0">未启用</Option>
                </Select>
                <Input
                    class="w-input"
                    v-model="searchKey"
                    clearable
                    placeholder="采集点名称"
                />
                <Button
                    type="primary"
                    @click="loadPage(1)"
                    style="width: 51px; height: 35px"
                >
                    <Icon type="ios-search" size="14" />
                </Button>
                <Button @click="cancel" class="btn">
                    <i
                        class="iconfont icon-gengxin"
                        style="font-size: 14px; margin-right: 5px"
                    ></i>
                </Button>
            </Col>
        </Row>
        <Table
            class="m-table"
            border
            stripe
            :columns="columns"
            :data="datalist"
        ></Table>
        <div class="page">
            <Page
                :total="count"
                :current="pageNo"
                :page-size="pageSize"
                show-total
                show-elevator
                @on-change="loadPage"
            />
        </div>
        <Modal
            v-model="fundcode"
            :title="title"
            :footer="null"
            :mask-closable="false"
            :width="500"
            styles="padding: none;margin: none"
        >
            <!-- 控制弹窗右上角x号是否显示 :closable="false" -->
            <Form
                ref="formInline"
                :model="info"
                :rules="infoRules"
                inline
                :label-width="120"
            >
                <FormItem prop="locationName" label="采集点名称：">
                    <Input
                        class="w-input"
                        v-model="info.locationName"
                        :maxlength="12"
                        placeholder="请输入采集点名称（12个汉字以内）"
                    />
                </FormItem>
                <FormItem prop="shq" label="采集地点：">
                    <!-- <Input
                        class="w-input"
                        v-model="info.longitude"
                        :maxlength="20"
                        placeholder="经度"
                    />
                    <br />
                    <Input
                        class="w-input"
                        v-model="info.latitude"
                        :maxlength="20"
                        placeholder="纬度"
                        style="margin-top:15px"
                    />
                    <br />  -->
                    <Input
                        class="w-input"
                        v-model="info.shq"
                        :maxlength="20"
                        placeholder="省、市、区、乡镇、街道"
                        disabled
                    />
                    <span @click="showMapComponent = true">
                        <i
                            class="iconfont icon-position"
                            style="font-size: 20px"
                        ></i>
                    </span>
                    <br />
                    <Input
                        class="w-input"
                        v-model="info.address"
                        :maxlength="20"
                        placeholder="请输入详细地址（小区、门牌号）"
                        style="margin-top: 15px"
                    />
                </FormItem>
                <FormItem prop="status" label="是否启用：">
                    <div class="w-input">
                        <iSwitch v-model="info.status" size="large">
                            <span slot="open">启用</span>
                            <span slot="close">禁用</span>
                        </iSwitch>
                    </div>
                </FormItem>
                <br />
                <FormItem label="采集点二维码：">
                    <img
                        v-if="!id"
                        src="../../../assets/images/erweima.png"
                        alt=""
                        class="QRCode"
                    />
                    <div class="qrcodeBox" v-if="id">
                        <div id="qrCode" class="qrcode" ref="qrCodeUrl"></div>
                        <div class="qrcodeBtn">
                            <Button type="primary" @click="bindQRCode(id)">
                                重新生成
                            </Button>
                            <Button type="primary" @click="downqrCode">
                                下载图片
                            </Button>
                        </div>
                    </div>
                </FormItem>
            </Form>
            <div slot="footer" class="btn-group" style="text-align: center">
                <Button
                    type="primary"
                    @click="submit('formInline')"
                    style="width: 75px; height: 35px"
                    :disabled="disabledfundcode"
                >
                    <Icon type="ios-checkmark" style="margin-right: 5px" />保存
                </Button>
                <Button
                    @click="closefundcode"
                    style="width: 75px; height: 35px"
                >
                    <i
                        class="iconfont icon-butongyi"
                        style="font-size: 14px; margin-right: 5px"
                    ></i
                    >取消
                </Button>
            </div>
        </Modal>
        <Modal
            @on-cancel="cancelMap"
            v-model="showMapComponent"
            width="100%"
            :closable="false"
            :mask-closable="false"
        >
            <div style="height: 800px; overflow-y: scroll">
                <baidu-map
                    v-bind:style="mapStyle"
                    class="bm-view"
                    ak="vqP7LHN9LD033eGnrpFDdvvD"
                    :center="center"
                    :zoom="zoom"
                    :scroll-wheel-zoom="true"
                    @click="getClickInfo"
                    @moving="syncCenterAndZoom"
                    @moveend="syncCenterAndZoom"
                    @zoomend="syncCenterAndZoom"
                    style="width: 100%; height: 100%"
                >
                    <bm-view style="width: 100%; height: 100%"></bm-view>
                    <bm-marker
                        :position="{ lng: center.lng, lat: center.lat }"
                        :dragging="true"
                        animation="BMAP_ANIMATION_BOUNCE"
                    >
                    </bm-marker>
                    <bm-control :offset="{ width: '10px', height: '10px' }">
                        <bm-auto-complete
                            v-model="keyword"
                            :sugStyle="{ zIndex: 9999 }"
                        >
                            <input
                                type="text"
                                placeholder="请输入搜索关键字"
                                class="serachinput"
                            />
                        </bm-auto-complete>
                    </bm-control>
                    <bm-local-search
                        :keyword="keyword"
                        :auto-viewport="true"
                        style="width: 0px; height: 0px; overflow: hidden"
                    ></bm-local-search>
                </baidu-map>
            </div>

            <div slot="footer" style="margin-top: 0px">
                <Button
                    @click="cancelMap"
                    type="ghost"
                    style="width: 60px; height: 36px"
                    >取消
                </Button>
                <Button
                    type="primary"
                    style="width: 60px; height: 36px"
                    @click="confirm"
                    >确定</Button
                >
            </div>
        </Modal>
    </div>
</template>

<script>
import api from '@/api/commonApi';
import QRCode from 'qrcodejs2';
import { Encrypt, Decrypt } from '../../../plugins/aes.js';
import {
    BaiduMap,
    BmControl,
    BmView,
    BmAutoComplete,
    BmLocalSearch,
    BmMarker
} from 'vue-baidu-map';
export default {
    components: {
        QRCode: QRCode,
        BaiduMap,
        BmControl,
        BmView,
        BmAutoComplete,
        BmLocalSearch,
        BmMarker
    },
    data() {
        return {
            showMapComponent: this.value,
            keyword: '',
            mapStyle: {
                width: '100%',
                height: this.mapHeight + 'px'
            },
            center: { lng: 114.635313, lat: 38.055966 },
            zoom: 15,
            searchKey: '',
            searchStatus: '',
            columns: [
                {
                    title: '排序',
                    key: 'iNum',
                    align: 'center',
                    width: 100,
                    render: (h, params) => {
                        let iNum =
                            (this.pageNo - 1) * this.pageSize +
                            params.index +
                            1;
                        return h('span', iNum);
                    }
                },
                {
                    title: '采集点名称',
                    key: 'locationName',
                    align: 'center'
                    // width: 300
                },
                {
                    title: '采集地点',
                    key: 'address',
                    align: 'center'
                    // width: 300
                },
                {
                    title: '状态',
                    key: 'status',
                    align: 'center',
                    width: 300,
                    render: (h, params) => {
                        let status = params.row.status;
                        let statusText = status == '1' ? '启用' : '停用';
                        return h('span', {
                            domProps: {
                                innerHTML: statusText
                            }
                        });
                    }
                },
                {
                    title: '设置',
                    key: 'operate',
                    align: 'center',
                    width: 100,
                    render: (h, params) => {
                        let id = params.row.id;
                        return [
                            h(
                                'span',
                                {
                                    attrs: {
                                        href: 'javascript:void(0);'
                                    },
                                    style: {
                                        color: '#5362e1',
                                        margin: '0px 6px'
                                    },
                                    on: {
                                        click: () => {
                                            (this.fundcode = true),
                                                (this.title = '编辑采集点信息');
                                            this.id = id;
                                            this.$refs.formInline.fields[0].validateMessage =
                                                '';
                                            this.$refs.formInline.fields[0].validateState =
                                                '';
                                            this.$refs.formInline.fields[1].validateState =
                                                '';
                                            this.$refs.formInline.fields[1].validateMessage =
                                                '';
                                            this.$axios
                                                .post(api.findLocationById, {
                                                    id: id
                                                })
                                                .then((resp) => {
                                                    if (resp.data.object) {
                                                        let ret =
                                                            resp.data.object;
                                                        this.info = ret;
                                                        this.info.status =
                                                            Boolean(
                                                                Number(
                                                                    ret.status
                                                                )
                                                            );
                                                        this.bindQRCode(
                                                            this.id
                                                        );
                                                        if (ret.villagesName) {
                                                            this.info.shq =
                                                                ret.provinceName +
                                                                ret.cityName +
                                                                ret.areaName +
                                                                ret.streetsName +
                                                                ret.villagesName;
                                                        } else if (
                                                            ret.streetsName
                                                        ) {
                                                            this.info.shq =
                                                                ret.provinceName +
                                                                ret.cityName +
                                                                ret.areaName +
                                                                ret.streetsName;
                                                        } else {
                                                            this.info.shq =
                                                                ret.provinceName +
                                                                ret.cityName +
                                                                ret.areaName;
                                                        }
                                                    } else {
                                                        this.$Message.info(
                                                            '数据错误'
                                                        );
                                                    }
                                                })
                                                .catch((err) => {
                                                    // this.$Message.info("服务器超时，请重新访问")
                                                });
                                        }
                                    }
                                },
                                '编辑'
                            )
                        ];
                    }
                }
            ],
            datalist: [],
            count: 0,
            pageSize: 10,
            pageNo: 1,
            id: null,
            fundcode: false,
            title: '',
            info: {
                locationName: '',
                longitude: '114.544403', //经度
                latitude: '38.034165', //纬度
                address: '', //详细地址
                status: true, //状态 0 停用 1启用
                shq: '北京市朝阳区西大望路15号-5号楼'
            },
            infoRules: {
                locationName: [
                    {
                        required: true,
                        message: '采集点名称不能为空',
                        trigger: 'change'
                    }
                ],
                shq: [
                    {
                        required: true,
                        message: '省、市、区、乡镇、街道不能为空',
                        trigger: 'change' //blur
                    }
                ],
                longitude: [
                    {
                        required: true,
                        message: '经度不能为空',
                        trigger: 'change' //blur
                    }
                ],
                latitude: [
                    {
                        required: true,
                        message: '纬度不能为空',
                        trigger: 'change' //blur
                    }
                ],
                status: [
                    {
                        required: true,
                        message: '请选择启用状态',
                        trigger: 'change',
                        type: 'boolean'
                    }
                ]
            },
            qrcode: '',
            appid: '',
            disabledfundcode: false
        };
    },
    created() {
        this.searchKey = this.$route.query.searchKey
            ? this.$route.query.searchKey
            : '';
        let breadList = [
            { path: '/index', title: '首页' },
            {
                path: '/index/maintain/configurationWarehouse/index',
                title: '配置仓'
            },
            {
                path: '/index/maintain/name/list',
                title: '疾病字典'
            }
        ];
        this.$emit('changeBreadList', breadList);
    },
    mounted() {
        let pageNo = this.$route.query.pageNo
            ? parseInt(this.$route.query.pageNo)
            : 1;
        //上来就加载第一页数据
        this.loadPage(pageNo);
        this.getAppid();
    },
    watch: {
        value: function (currentValue) {
            this.showMapComponent = currentValue;
            if (currentValue) {
                this.keyword = '';
            }
        }
    },
    props: {
        value: Boolean,
        mapHeight: {
            type: Number,
            default: 800
        }
    },
    methods: {
        /***
         * 地图点击事件。
         */
        getClickInfo(e) {
            this.center.lng = e.point.lng;
            this.center.lat = e.point.lat;
            //用所定位的经纬度查找所在地省市街道等信息
            let point = new BMap.Point(e.point.lng, e.point.lat);
            let gc = new BMap.Geocoder();
            let that = this;
            gc.getLocation(point, function (rs) {
                // console.log(rs)
                let addComp = rs.addressComponents;
                that.info.provinceName = addComp.province;
                that.info.cityName = addComp.city;
                that.info.areaName = addComp.district;
                that.info.streetsName = addComp.street;
                that.info.villagesName = addComp.town;
                that.info.shq = rs.address;
            });
            this.info.longitude = e.point.lng;
            this.info.latitude = e.point.lat;
            this.info.shq = that.info.shq;
        },
        syncCenterAndZoom(e) {
            const { lng, lat } = e.target.getCenter();
            this.center.lng = lng;
            this.center.lat = lat;
            this.zoom = e.target.getZoom();
        },
        /***
         * 确认
         */
        confirm: function () {
            this.showMapComponent = false;
            this.$emit('map-confirm', this.center);
        },
        /***
         * 取消
         */
        cancelMap: function () {
            this.showMapComponent = false;
            this.$emit('cancel', this.showMapComponent);
        },

        getAppid() {
            let hospitalId = sessionStorage.getItem('hospitalId')
                ? sessionStorage.getItem('hospitalId')
                : null;
            this.$axios
                .post(api.findAppidByHospitalId, { hospitalId })
                .then((resp) => {
                    if (resp.data.success) {
                        this.appid = resp.data.object.appId;
                        console.log('44444', this.appid);
                    } else {
                        this.$Message.info('不允许访问');
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        bindQRCode(id) {
            //给id加密
            let body = Encrypt(
                this.$store.state.loginkeytemp,
                this.$store.state.iv,
                id
                // JSON.stringify(id)
            );
            body = body.replace(/\+/g, '%2B');
            // 给id解密（此处用不到解密）
            // let seng = Decrypt(this.$store.state.loginkeytemp, this.$store.state.iv, body);
            // console.log('解密串',seng)
            // 扫描二维码打开的页面，以本地地址为例
            // let localhostUrl = window.location.href; //获取到测试or正式环境路径等等
            // localhostUrl = localhostUrl.split("#");
            // localhostUrl = localhostUrl[0];
            // console.log("本地url：", localhostUrl)
            //生成二维码js必须在 this.$nextTick(function(){调用})或setTimeout(() => { 调用 }, 100)，是为了确保二维码容器DOM已经存在。
            this.$nextTick(function () {
                //需要注意的一点是，在下一次二维码生成之前，需要把之前生成的二维码先删除，不然会生成很多个二维码，可以使用以下方法删除或 document.getElementById("qrCode").innerHTML = ""
                this.$refs.qrCodeUrl.innerHTML = ''; // 用于清空生成的二维码
                let qrCode = new QRCode(this.$refs.qrCodeUrl, {
                    // text: 'https://blog.csdn.net/weixin_43760328',    // 需要生成二维码的内容
                    // text: `${localhostUrl}#/writtenSign?id=${this.orderListId}`,    // 需要生成二维码的内容
                    text: `http://health-jh.natapp1.cc/imcpage/#/nucleicAcid/nucleicRregistration?id=${body}&appid=${this.appid}`, // 需要生成二维码的内容
                    width: 150,
                    height: 150,
                    colorDark: '#333333', //二维码颜色
                    colorLight: '#ffffff', //二维码背景色
                    correctLevel: QRCode.CorrectLevel.L //容错率，L/M/H
                });
                this.qrcode = qrCode;
            });
        },
        // 点击下载app二维码
        downqrCode(name) {
            var canvasData =
                this.$refs.qrCodeUrl.getElementsByTagName('canvas');
            var a = document.createElement('a');
            var event = new MouseEvent('click'); // 创建一个单击事件
            a.href = canvasData[0].toDataURL('image/png');
            a.download = 'drcQrcode';
            a.dispatchEvent(event); // 触发a的单击事件
        },
        srInput() {
            this.info.phone = this.info.phone.replace(/[^0-9]/g, '');
        },
        cancel() {
            this.searchKey = '';
            this.searchStatus = '';
            this.loadPage(1);
        },
        //加载列表数据
        loadPage(pageNo) {
            this.pageNo = parseInt(pageNo);
            var params = {};
            params.searchKey = this.searchKey.trim();
            params.searchStatus = this.searchStatus;
            params.pageNo = pageNo;
            params.pageSize = this.pageSize;
            this.$axios
                .post(api.findLocationPage, params)
                .then((resp) => {
                    if (resp.data.success) {
                        this.count = resp.data.object.total;
                        if (resp.data.object.records) {
                            this.datalist = resp.data.object.records;
                        } else {
                            this.datalist = [];
                            this.count = 0;
                        }
                    } else {
                        this.$Message.info('不允许访问');
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        add() {
            this.fundcode = true;
            this.title = '添加采集点信息';
            this.id = '';
        },
        closefundcode() {
            (this.info = {
                locationName: '',
                longitude: '', //经度
                latitude: '', //纬度
                address: '', //详细地址
                status: true, //状态 0 停用 1启用
                shq: ''
            }),
                (this.id = '');
            this.fundcode = false;
        },
        //提交
        submit(name) {
            (this.disabledfundcode = true),
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.info.status = Number(this.info.status);
                        let operateApi = '';
                        let noticeMsg = '';
                        if (this.id) {
                            operateApi = api.updateLocation;
                            noticeMsg = '修改';
                        } else {
                            noticeMsg = '添加';
                            operateApi = api.saveLocation;
                        }
                        this.$axios
                            .post(operateApi, this.info)
                            .then((resp) => {
                                if (resp.data.code == 1) {
                                    if (noticeMsg == '添加') {
                                        this.id = resp.data.object;
                                        this.bindQRCode(this.id);
                                    }
                                    //   公用方法
                                    this.$Message.success(resp.data.message);
                                    setTimeout(() => {
                                        (this.disabledfundcode = false),
                                            this.closefundcode();
                                        this.loadPage(this.pageNo);
                                    }, 1000);
                                } else {
                                    (this.disabledfundcode = false),
                                        (this.info.status = Boolean(
                                            this.info.status
                                        ));
                                    this.$Message.error(resp.data.message);
                                }
                            })
                            .catch((err) => {
                                (this.disabledfundcode = false),
                                    (this.info.status = Boolean(
                                        this.info.status
                                    ));
                                console.log(err);
                            });
                    } else {
                        (this.disabledfundcode = false),
                            this.$Message.error('请完整填写必填项');
                        this.info.status = Boolean(this.info.status);
                    }
                });
        }
    }
};
</script>
<style lang="less" scoped>
.datalist {
    padding: 20px;
    width: 100%;
    background: #ffffff;
    box-sizing: border-box;
    .w-select {
        width: 100px;
    }
    .w-input {
        width: 200px;
    }
    .m-table {
        margin: 10px 0;
    }
    .addbutton {
        background-color: #21c780;
        border: 1px solid #21c780;
    }
    .page {
        text-align: center;
        margin: 20px 0;
    }
}
.w-select {
    width: 100px;
}
.w-input {
    width: 300px;
}
.qrcodeBox {
    display: flex;
    .qrcode {
        display: inline-block;
        width: 162px;
        height: 162px;
        background-color: #fff; //设置白色背景色
        padding: 6px; // 利用padding的特性，挤出白边
        box-sizing: border-box;
    }
    .qrcodeBtn {
        display: flex;
        flex-direction: column;
        margin-left: 20px;
    }
    .qrcodeBtn :first-child {
        margin-top: 10px;
        margin-bottom: 15px;
    }
}

.inputnumber {
    width: 150px;
    background: #fff;
    border: none;
    outline: none;
    text-indent: 10px;
    line-height: 30px;
    border: 1px solid #ddd;
    border-radius: 4px;
    color: #666;
}
.inputnumber:focus {
    border-color: #5362e1;
}
.QRCode {
    width: 150px;
    height: 150px;
}
/deep/ .ivu-modal-wrap {
    .ivu-modal {
        float: right !important;
        background-color: #fff;
        border-radius: 10px;
        top: 0px;
        height: 100%;
    }
}
.serachinput {
    width: 300px;
    box-sizing: border-box;
    padding: 9px;
    border: 1px solid #dddee1;
    line-height: 20px;
    font-size: 16px;
    height: 38px;
    color: #333;
    position: relative;
    border-radius: 4px;
    -webkit-box-shadow: #666 0px 0px 10px;
    -moz-box-shadow: #666 0px 0px 10px;
    box-shadow: #666 0px 0px 10px;
}
.bm-view {
    width: 100%;
    height: 100%;
}
</style>